﻿using System;
using System.Security.Cryptography;

namespace FDL.Library.Numeric
{
    /// <summary>
    /// https://scottlilly.com/create-better-random-numbers-in-c/
    /// If you use the System.Random class, and create new instance of it with every use, you’ll get the same numbers, in the same order.
    /// To see the problem, run a program that uses a System.Random object to generate 10 random numbers. Write those numbers down, and then stop the program. Now, run the program again. You’ll see that it gives you the same 10 numbers, in the exact same order.
    ///This happens because the random number generator initializes itself with a seed value.But it’s the same seed value each time you run the program.So, you get the same results.This is often called “pseudo-random” numbers.
    /// pseudo-random 伪随机
    /// A better method is to use the random number generator in the cryptography library of the .Net framework.
    /// 更好的方法是使用 .Net 框架的密码学库中的随机数生成器。
    /// </summary>
    public static class RandomNumber
    {
        private static readonly RNGCryptoServiceProvider _generator = new RNGCryptoServiceProvider();

        public static int Between(int minimumValue, int maximumValue)
        {
            byte[] randomNumber = new byte[1];

            _generator.GetBytes(randomNumber);

            double asciiValueOfRandomCharacter = Convert.ToDouble(randomNumber[0]);

            // We are using Math.Max, and substracting 0.00000000001, 
            // to ensure "multiplier" will always be between 0.0 and .99999999999
            // Otherwise, it's possible for it to be "1", which causes problems in our rounding.
            double multiplier = Math.Max(0, (asciiValueOfRandomCharacter / 255d) - 0.00000000001d);

            // We need to add one to the range, to allow for the rounding done with Math.Floor
            int range = maximumValue - minimumValue + 1;

            double randomValueInRange = Math.Floor(multiplier * range);

            return (int)(minimumValue + randomValueInRange);
        }
    }
}